package com.will.txj.aj.global.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @author: wen-yi;
 * @date: 2021/12/9 22:34;
 * @Description: feign调用服务时，会丢失请求头信息。需要在这里把认证信息收到添加上去
 */
@Slf4j
@Configuration
public class FeignTokenInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        //log.info("======上下文中获取原请求信息======");
        HttpServletRequest request = ((ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes()).getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String HeadValue = request.getHeader(headerName);
            //log.info("===原请求头信息=== headName: {}, headValue: {}", headerName, HeadValue);
            requestTemplate.header(headerName, HeadValue);
        }
        // requestTemplate.header("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJiaXJ0aGRheSI6bnVsbCwidUlkIjoyLCJhdWQiOlsiYWpfc2VydmVyIl0sInVzZXJfbmFtZSI6ImFqIiwic2NvcGUiOlsiYWxsIl0sInNleCI6bnVsbCwibmlja25hbWUiOiLnnaHop4kiLCJleHAiOjE2MzkxMDA1ODUsImF1dGhvcml0aWVzIjpbInNob3ciLCJST0xFX3VzZXIiXSwianRpIjoiOWZlOTJmMjctYThjOS00M2ZmLTgxY2YtOTVmNzM1ZTNiYzY3IiwiY2xpZW50X2lkIjoidXNlciIsInVzZXJuYW1lIjoiYWoifQ.K-WJ0dpnYj-YpkD3jNlN-Oafb89uTUpBMbhwZ4ABpyo");
        //log.info("======添加请求头信息完毕======");
    }
}
